// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package container

import (
	"encoding/json"
	"gitee.com/tugoer/psys/models"
	"sync"
)

const adJsonKey = "advert"

func readAdvertisementData() (data []byte) {
	return []byte(models.GetJsonData(adJsonKey))
}

func writeAdvertisementData(data []byte) error {
	return models.SetJsonData(adJsonKey, string(data))
}

var Advertisements = &advertisement{}

type advertisement struct {
	data []*models.Advertisement
	mu   sync.RWMutex
}

var defaultAdvertisements = []*models.Advertisement{
	{
		Kind: "",
		Img:  "",
		Url:  "https://www.baidu.com",
	},
}

func (ec *advertisement) Save(jsonData string) (err error) {
	ec.mu.Lock()
	defer ec.mu.Unlock()
	var ads []*models.Advertisement
	err = json.Unmarshal([]byte(jsonData), &ads)
	if err != nil {
		return err
	}
	data, err := json.Marshal(ads)
	if err != nil {
		return err
	}
	err = writeAdvertisementData(data)
	if err != nil {
		return err
	}
	ec.data = ads
	return nil
}

func (ec *advertisement) Get(page, limit int) (ads []*models.Advertisement, err error) {
	ec.mu.Lock()
	defer ec.mu.Unlock()
	ads = ec.data
	if ads == nil {
		// 本地获取数据
		data := readAdvertisementData()
		if len(data) == 0 {
			// 设置默认数据
			ads = defaultAdvertisements
			data, err := json.Marshal(ads)
			if err != nil {
				return nil, err
			}
			err = writeAdvertisementData(data)
			if err != nil {
				return nil, err
			}
		} else {
			// 解析本地数据
			err = json.Unmarshal(data, &ads)
			if err != nil {
				return nil, err
			}
		}
		ec.data = ads
	}
	start := limit * (page - 1)
	end := limit * page
	if start < 0 {
		start = 0
	}
	if lidx := len(ads); end > lidx {
		end = lidx
	}
	if start < end {
		return ads[start:end], nil
	} else {
		return nil, nil
	}
}
